/**
 * 
 */
package com.ls.lserp.common.persistence;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.utils.CookieUtils;

import com.ls.lserp.common.utils.PropertiesLoader;
import com.ls.lserp.common.utils.SpringContextHolder;

/**
 * 分页类
 * 
 * @author
 * @version 2013-7-2
 * @param <T>
 */
public class Page<T> {

	private int pageNo = 1; // 当前页码
	private int pageSize = Integer.valueOf(Global.getConfig("page.pageSize")); // 页面大小，设置为“-1”表示不进行分页（分页无效）
	protected String PAGEGO = "跳转"; // 跳转按钮名称
	protected String PAGENEXT = "下一页&nbsp;》"; // 下一页按钮名称
	protected String PAGEPREVIOUS = "《&nbsp;上一页"; // 上一页按钮名称
	private long count;// 总记录数，设置为“-1”表示不查询总数
	private int first;// 首页索引
	private int last;// 尾页索引
	private int prev;// 上一页索引
	private int next;// 下一页索引

	private boolean firstPage;// 是否是第一页
	private boolean lastPage;// 是否是最后一页

	private int length = 6;// 显示页面长度
	private int slider = 1;// 前后显示页面长度

	private List<T> list = new ArrayList<T>();

	private String orderBy = ""; // 标准查询有效， 实例： updatedate desc, name asc

	private String funcName = "paginationMothod"; // 设置点击页码调用的js函数名称，默认为page，在一页有多个分页对象时使用。

	private String message = ""; // 设置提示消息，显示在“共n条”之后

	private String url = "";// 使用ajax调用时，要用的url(函数的附加参数，第三个参数值)。

	private String listNames = "";// 使用ajax调用时，要用的结果名(函数的附加参数，第四个参数值)。

	private String searchParam = "";// 分页检索用参数条件

	/**
	 * 分页检索用参数条件
	 * 
	 * @param searchParam
	 * @return
	 */
	private String getSearchParam() {
		return this.searchParam;
	}

	/**
	 * 分页检索用参数条件
	 * 
	 * @param searchParam
	 */
	private void setSearchParam(String searchParam) {
		this.searchParam = searchParam;
	}

	public Page() {
		this.pageSize = -1;
	}

	/**
	 * 国际化
	 * 
	 * @param message
	 * @return
	 */
	public String getTextMessage(String message) {

		return SpringContextHolder.getApplicationContext().getMessage(message, null, null);

	}

	private static List<Integer> perPageList = new ArrayList<Integer>();

	static {
		perPageList.add(10);
		perPageList.add(20);
		perPageList.add(50);
		perPageList.add(100);
		/* perPageList.add(200); */
	}

	public static List<Integer> getPerPageList() {
		return perPageList;
	}

	public static void setPerPageList(List<Integer> perPageList) {
		Page.perPageList = perPageList;
	}

	/*
	 * public Page() { if (perPageList.size() > 0) { numPerPage =
	 * perPageList.get(0); } }
	 */
	/**
	 * 构造方法
	 * 
	 * @param request
	 *            传递 repage 参数，来记住页码
	 * @param response
	 *            用于设置 Cookie，记住页码
	 */
	public Page(HttpServletRequest request, HttpServletResponse response) {
		this(request, response, -2);
	}

	/**
	 * 构造方法
	 * 
	 * @param request
	 *            传递 repage 参数，来记住页码
	 * @param response
	 *            用于设置 Cookie，记住页码
	 * @param defaultPageSize
	 *            默认分页大小，如果传递 -1 则为不分页，返回所有数据
	 */
	public Page(HttpServletRequest request, HttpServletResponse response, int defaultPageSize) {
		// 获取当前调用的url
		this.setUrl(request.getRequestURI());
		this.setListNames(request.getAttribute(Global.LIST_NAME).toString());
		// 取得画面检索条件
		if (request.getAttribute(Global.SEARCH_PAEAM) == null) {
			this.setSearchParam("");
		} else {
			this.setSearchParam(request.getAttribute(Global.SEARCH_PAEAM).toString());
		}
		// 设置页码参数（传递repage参数，来记住页码）
		String no = request.getParameter("pageNo");
		if (StringUtils.isNumeric(no)) {
			CookieUtils.setCookie(response, "pageNo", no);
			this.setPageNo(Integer.parseInt(no));
		} else if (request.getParameter("repage") != null) {
			no = CookieUtils.getCookie(request, "pageNo");
			if (StringUtils.isNumeric(no)) {
				this.setPageNo(Integer.parseInt(no));
			}
		}
		// 设置页面大小参数（传递repage参数，来记住页码大小）
		String size = request.getParameter("pageSize");
		if (StringUtils.isNumeric(size)) {
			CookieUtils.setCookie(response, "pageSize", size);
			this.setPageSize(Integer.parseInt(size));
		} else if (request.getParameter("repage") != null) {
			no = CookieUtils.getCookie(request, "pageSize");
			if (StringUtils.isNumeric(size)) {
				this.setPageSize(Integer.parseInt(size));
			}
		} else if (defaultPageSize != -2) {
			this.pageSize = defaultPageSize;
		}

		if (defaultPageSize == -1) {
			this.pageSize = defaultPageSize;
		}
		// 设置排序参数
		String orderBy = request.getParameter("orderBy");
		if (StringUtils.isNotBlank(orderBy)) {
			this.setOrderBy(orderBy);
		}

	}

	/**
	 * 构造方法
	 * 
	 * @param pageNo
	 *            当前页码
	 * @param pageSize
	 *            分页大小
	 */
	public Page(int pageNo, int pageSize) {
		this(pageNo, pageSize, 0);
	}

	/**
	 * 构造方法
	 * 
	 * @param pageNo
	 *            当前页码
	 * @param pageSize
	 *            分页大小
	 * @param count
	 *            数据条数
	 */
	public Page(int pageNo, int pageSize, long count) {
		this(pageNo, pageSize, count, new ArrayList<T>());
	}

	/**
	 * 构造方法
	 * 
	 * @param pageNo
	 *            当前页码
	 * @param pageSize
	 *            分页大小
	 * @param count
	 *            数据条数
	 * @param list
	 *            本页数据对象列表
	 */
	public Page(int pageNo, int pageSize, long count, List<T> list) {
		this.setCount(count);
		this.setPageNo(pageNo);
		this.pageSize = pageSize;
		this.list = list;
	}

	/**
	 * 初始化参数
	 */
	public void initialize() {

		// 1
		this.first = 1;

		this.last = (int) (count / (this.pageSize < 1 ? 20 : this.pageSize) + first - 1);

		if (this.count % this.pageSize != 0 || this.last == 0) {
			this.last++;
		}

		if (this.last < this.first) {
			this.last = this.first;
		}

		if (this.pageNo <= 1) {
			this.pageNo = this.first;
			this.firstPage = true;
		}

		if (this.pageNo >= this.last) {
			this.pageNo = this.last;
			this.lastPage = true;
		}

		if (this.pageNo < this.last - 1) {
			this.next = this.pageNo + 1;
		} else {
			this.next = this.last;
		}

		if (this.pageNo > 1) {
			this.prev = this.pageNo - 1;
		} else {
			this.prev = this.first;
		}

		// 2
		if (this.pageNo < this.first) {// 如果当前页小于首页
			this.pageNo = this.first;
		}

		if (this.pageNo > this.last) {// 如果当前页大于尾页
			this.pageNo = this.last;
		}

	}

	/**
	 * 默认输出当前分页标签 <div class="page">${page}</div>
	 */
	@Override
	public String toString() {
		int pageCount = 0;
		// 实例化StringBuilder对象
		StringBuilder strbuilder = new StringBuilder();
		strbuilder.append("<div class=\"pageArea clearfix\">\n");
		strbuilder.append("<div class=\"pageCenter\">\n");
		if (pageNo == first) {// 如果是首页
			strbuilder.append("<span class=\"pageBtn disabled\">" + PAGEPREVIOUS + "</span>\n");
		} else {
			strbuilder.append("<span  class=\"pageBtn\" onclick=\"" + funcName + "(" + prev + "," + pageSize + ",'"
					+ this.url + "','" + this.listNames + "','" + this.getSearchParam() + "');\" >" + PAGEPREVIOUS
					+ "</span>\n");
		}

		strbuilder.append(" <span>");

		int begin = pageNo - (length / 2);

		if (begin < first) {
			begin = first;
		}

		int end = begin + length - 1;

		if (end >= last) {
			end = last;
			begin = end - length + 1;
			if (begin < first) {
				begin = first;
			}
		}

		if (begin > first) {
			int i = 0;
			for (i = first; i < first + slider && i < begin; i++) {
				strbuilder.append("<span onclick=\"" + funcName + "(" + i + "," + pageSize + ",'" + this.url + "','"
						+ this.listNames + "','" + getSearchParam() + "');\">" + (i + 1 - first) + "</a></span>\n");
			}
			if (i < begin) {
				strbuilder.append("<span class=\"disabled\"></span>\n");
			}

		}

		for (int i = begin; i <= end; i++) {
			if (i == pageNo) {
				strbuilder.append("<span class=\"active\">" + (i + 1 - first) + "</span>\n");
			} else {
				strbuilder.append("<span onclick=\"" + funcName + "(" + i + "," + pageSize + ",'" + this.url + "','"
						+ this.listNames + "','" + getSearchParam() + "');\">" + (i + 1 - first) + "</span>\n");
			}
		}

		if (last - end > slider) {
			strbuilder.append("<span class=\"disabled\">...</span>\n");
			end = last - slider;
		}

		for (int i = end + 1; i <= last; i++) {
			strbuilder.append("<span onclick=\"" + funcName + "(" + i + "," + pageSize + ",'" + this.url + "','"
					+ this.listNames + "','" + getSearchParam() + "');\">" + (i + 1 - first) + "</a></span>\n");
		}

		strbuilder.append(" </span>");
		if (pageNo == last) {
			strbuilder.append("<span class=\"pageBtn  disabled\">" + PAGENEXT + "</span>\n");
		} else {
			strbuilder.append(
					"<span  class=\"pageBtn\" onclick=\"" + funcName + "(" + next + "," + pageSize + ",'" + this.url
							+ "','" + this.listNames + "','" + getSearchParam() + "');\" >" + PAGENEXT + "</span>\n");
		}
		strbuilder.append(" </div>\n");
		strbuilder.append("<div class=\"pageLeft\">\n");
		strbuilder.append(" <span>共" + count + "条</span>\n");
		strbuilder.append(" <span>每页显示</span>\n");
		strbuilder.append("<select  onchange=\"" + funcName + "(1,this.value, '" + this.url + "','" + this.listNames
				+ "','" + getSearchParam() + "');\">");
		for (int i = 0; i < perPageList.size(); i++) {
			if (perPageList.get(i).equals(pageSize)) {
				strbuilder.append(" <option selected = \"selected\" value = '" + perPageList.get(i) + "'>"
						+ perPageList.get(i) + "</option>\n");
			} else {
				strbuilder
						.append(" <option value = '" + perPageList.get(i) + "'>" + perPageList.get(i) + "</option>\n");
			}

		}
		strbuilder.append(" </select>\n");
		strbuilder.append(" <span>条</span>\n");
		strbuilder.append("  </div>\n");
		strbuilder.append(" <div class=\"pageRight\">\n");
		if (end == 1) {
			pageCount = end;
		} else {
			pageCount = end +1;
		}
		strbuilder.append(" <span>共" + pageCount + "页</span>\n");
		strbuilder.append("          <span>跳到</span>\n");
		strbuilder.append("          <input id='pageGo' value='" + pageNo + "' />\n");
		strbuilder.append("          <span>页</span>\n");
		if (pageCount == 1) {
			strbuilder.append("          <button type=\"button\"  class=\"btn-cj\">" + PAGEGO + "</button>\n");
		} else {
			strbuilder.append("          <button type=\"button\"  class=\"btn-cj\" onclick=\"" + funcName
					+ "(document.getElementById('pageGo').value," + pageSize + ",'" + this.url + "','" + this.listNames
					+ "','" + getSearchParam() + "');\">" + PAGEGO + "</button>\n");
		}
		strbuilder.append("      </div>\n");
		strbuilder.append(" </div>\n");
		return strbuilder.toString();
	}

	/**
	 * 获取分页HTML代码
	 * 
	 * @return
	 */
	public String getHtml() {
		return toString();
	}

	/**
	 * 获取设置总数
	 * 
	 * @return
	 */
	public long getCount() {
		return count;
	}

	/**
	 * 设置数据总数
	 * 
	 * @param count
	 */
	public void setCount(long count) {
		this.count = count;
		if (pageSize >= count) {
			pageNo = 1;
		}
	}

	/**
	 * 获取当前页码
	 * 
	 * @return
	 */
	public int getPageNo() {
		return pageNo;
	}

	/**
	 * 设置当前页码
	 * 
	 * @param pageNo
	 */
	public void setPageNo(int pageNo) {
		this.pageNo = pageNo;
	}

	/**
	 * 获取页面大小
	 * 
	 * @return
	 */
	public int getPageSize() {
		return pageSize;
	}

	/**
	 * 设置页面大小（最大500）
	 * 
	 * @param pageSize
	 */
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize <= 0 ? 10 : pageSize;// > 500 ? 500 : pageSize;
	}

	/**
	 * 首页索引
	 * 
	 * @return
	 */
	@JsonIgnore
	public int getFirst() {
		return first;
	}

	/**
	 * 尾页索引
	 * 
	 * @return
	 */
	@JsonIgnore
	public int getLast() {
		return last;
	}

	/**
	 * 获取页面总数
	 * 
	 * @return getLast();
	 */
	@JsonIgnore
	public int getTotalPage() {
		return getLast();
	}

	/**
	 * 是否为第一页
	 * 
	 * @return
	 */
	@JsonIgnore
	public boolean isFirstPage() {
		return firstPage;
	}

	/**
	 * 是否为最后一页
	 * 
	 * @return
	 */
	@JsonIgnore
	public boolean isLastPage() {
		return lastPage;
	}

	/**
	 * 上一页索引值
	 * 
	 * @return
	 */
	@JsonIgnore
	public int getPrev() {
		if (isFirstPage()) {
			return pageNo;
		} else {
			return pageNo - 1;
		}
	}

	/**
	 * 下一页索引值
	 * 
	 * @return
	 */
	@JsonIgnore
	public int getNext() {
		if (isLastPage()) {
			return pageNo;
		} else {
			return pageNo + 1;
		}
	}

	/**
	 * 获取本页数据对象列表
	 * 
	 * @return List<T>
	 */
	public List<T> getList() {
		return list;
	}

	/**
	 * 设置本页数据对象列表
	 * 
	 * @param list
	 */
	public Page<T> setList(List<T> list) {
		this.list = list;
		initialize();
		return this;
	}

	/**
	 * 获取查询排序字符串
	 * 
	 * @return
	 */
	@JsonIgnore
	public String getOrderBy() {
		// SQL过滤，防止注入
		String reg = "(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|"
				+ "(\\b(select|update|and|or|delete|insert|trancate|char|into|substr|ascii|declare|exec|count|master|into|drop|execute)\\b)";
		Pattern sqlPattern = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);
		if (sqlPattern.matcher(orderBy).find()) {
			return "";
		}
		return orderBy;
	}

	/**
	 * 设置查询排序，标准查询有效， 实例： updatedate desc, name asc
	 */
	public void setOrderBy(String orderBy) {
		this.orderBy = orderBy;
	}

	/**
	 * 获取点击页码调用的js函数名称 function ${page.funcName}(pageNo){location=
	 * "${ctx}/list-${category.id}${urlSuffix}?pageNo="+i;}
	 * 
	 * @return
	 */
	@JsonIgnore
	public String getFuncName() {
		return funcName;
	}

	/**
	 * 设置点击页码调用的js函数名称，默认为page，在一页有多个分页对象时使用。
	 * 
	 * @param funcName
	 *            默认为page
	 */
	public void setFuncName(String funcName) {
		this.funcName = funcName;
	}

	/**
	 * 设置提示消息，显示在“共n条”之后
	 * 
	 * @param message
	 */
	public void setMessage(String message) {
		this.message = message;
	}

	/**
	 * 分页是否有效
	 * 
	 * @return this.pageSize==-1
	 */
	@JsonIgnore
	public boolean isDisabled() {
		return this.pageSize == -1;
	}

	/**
	 * 是否进行总数统计
	 * 
	 * @return this.count==-1
	 */
	@JsonIgnore
	public boolean isNotCount() {
		return this.count == -1;
	}

	/**
	 * 获取 Hibernate FirstResult
	 */
	public int getFirstResult() {
		int firstResult = (getPageNo() - 1) * getPageSize();
		if (firstResult >= getCount()) {
			firstResult = 0;
		}
		return firstResult;
	}

	/**
	 * 获取 Hibernate MaxResults
	 */
	public int getMaxResults() {
		return getPageSize();
	}

	/**
	 * 获取当前的url
	 * 
	 * @return
	 */
	private String getUrl() {
		return url;
	}

	/**
	 * 获取当前的url
	 * 
	 * @return
	 */
	private void setUrl(String url) {
		this.url = url;
	}

	/**
	 * 获取结果数据的list名
	 * 
	 * @return
	 */
	private String getListNames() {
		return listNames;
	}

	/**
	 * 获取结果数据的list名
	 * 
	 * @return
	 */
	private void setListNames(String listNames) {
		this.listNames = listNames;
	}

	// /**
	// * 获取 Spring data JPA 分页对象
	// */
	// public Pageable getSpringPage(){
	// List<Order> orders = new ArrayList<Order>();
	// if (orderBy!=null){
	// for (String order : StringUtils.split(orderBy, ",")){
	// String[] o = StringUtils.split(order, " ");
	// if (o.length==1){
	// orders.add(new Order(Direction.ASC, o[0]));
	// }else if (o.length==2){
	// if ("DESC".equals(o[1].toUpperCase())){
	// orders.add(new Order(Direction.DESC, o[0]));
	// }else{
	// orders.add(new Order(Direction.ASC, o[0]));
	// }
	// }
	// }
	// }
	// return new PageRequest(this.pageNo - 1, this.pageSize, new Sort(orders));
	// }
	//
	// /**
	// * 设置 Spring data JPA 分页对象，转换为本系统分页对象
	// */
	// public void setSpringPage(org.springframework.data.domain.Page<T> page){
	// this.pageNo = page.getNumber();
	// this.pageSize = page.getSize();
	// this.count = page.getTotalElements();
	// this.list = page.getContent();
	// }
}
